package com.lovo.bbs.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.lovo.bbs.bo.BoardBo;
import com.lovo.bbs.bo.ForumBo;
import com.lovo.bbs.bo.ForumStatBo;
import com.lovo.bbs.bo.LinkBo;
import com.lovo.bbs.listener.VistorCounterListen;
import com.lovo.bbs.vo.BoardVo;
import com.lovo.bbs.vo.ForumStatVo;
import com.lovo.bbs.vo.ForumVo;
import com.lovo.bbs.vo.LinkVo;
import com.lovo.bbs.vo.LoginVo;

/**
 * 更新ServletContext数据,初始化request数据
 * 
 * @author tiancen2001
 * 
 */
public class UpdateGlobalFilter implements Filter {

	public void destroy() {

	}

	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		ServletContext context = req.getSession().getServletContext();

		// 取得所有板块列表
		ArrayList<BoardVo> boardList = (ArrayList<BoardVo>) context
				.getAttribute("boardList");
		// 更新板块列表
		if (boardList == null) {
			boardList = new BoardBo().getAllBoard();
			context.setAttribute("boardList", boardList);
		}

		// 取得所有论坛列表
		ArrayList<ForumVo> forumList = (ArrayList<ForumVo>) context
				.getAttribute("forumList");
		// 更新论坛列表和forumMap
		ForumBo forumBo = new ForumBo();
		if (forumList == null) {
			forumList = forumBo.getAllForum();
			//更新论坛列表
			context.setAttribute("forumList", forumList);
			//更新forumMap
			context.setAttribute("forumMap", forumBo.getForumMap(forumList));
		}

		// 取得所有友情链接列表
		ArrayList<LinkVo> linkList = (ArrayList<LinkVo>) context
				.getAttribute("linkList");
		if (linkList == null) {
			// 更新友情链接列表
			linkList = new LinkBo().getAllLink();
			context.setAttribute("linkList", linkList);
		}

		// 取得网站杂项信息
		ForumStatVo forumInfo = (ForumStatVo)context.getAttribute("forumInfo");
		//更新网站杂项信息
		if(forumInfo==null){
			forumInfo = new ForumStatBo().getForumInfo();
		}
		HashMap<String, LoginVo> onlineUser = (HashMap<String, LoginVo>) context
				.getAttribute("onlineUser");
		//更新在线会员数
		forumInfo.setMemberOLNum(onlineUser.size());
		//更新在线总人数
		forumInfo.setUserOLNum(VistorCounterListen.getVisitorNum());
		context.setAttribute("forumInfo", forumInfo);
		
		req.setAttribute("forumInfo", forumInfo);
		req.setAttribute("boardList", boardList);
		req.setAttribute("forumList", forumList);
		req.setAttribute("linkList", linkList);

		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}

}
